package edu.hubu.shop9.util;

import org.apache.velocity.shaded.commons.io.FilenameUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: waxijiang
 * @Date: 2021/7/28
 * @Content:
 */
public class FileUtils {
    public static String fileSave(MultipartFile file, String path) throws FileNotFoundException {
        System.out.println("文件名:" + file.getOriginalFilename());
        System.out.println("文件类型:" + file.getContentType());
        System.out.println("文件大小:" + file.getSize());


        String targetDir = ResourceUtils.getURL("classpath:").getPath() + "static" + path;
        System.out.println(targetDir);
        String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
        File dir = new File(targetDir, dateDir);
        // 不存在则创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String newFileNamePrefix =
                new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString();
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String newFileName = newFileNamePrefix + "." + extension;
        File targetFile = new File(dir, newFileName);

        // 上传文件
        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("上传成功");
        return path + "/" + dateDir + "/" + newFileName;
    }
}
